//
//  LibraryViewController.m
//  我的图书馆
//
//  Created by 孙  路 on 15-1-4.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "LibraryViewController.h"

#import "HoldingView.h"

#import "ListViewController.h"

#import "HoldingViewController.h"
//收藏文章cell
#import "LibraryTableViewCell.h"
//编辑文章
#import "EditArticleViewController.h"
//进入搜索界面
#import "SearchViewController.h"
//读取数据库
#import "DetailBace.h"
#import "DetailModel.h"
//进入webView
#import "DetailsViewController.h"
#import "ReadingRoomModel.h"
#import "DengLuViewController.h"
#import "HomePoltController.h"

//主色调
#define kBlueColor [UIColor colorWithRed:129/255.0 green: 198/255.0 blue: 221/255.0 alpha: 1.0]
@interface LibraryViewController ()
//我的下载
@property (nonatomic, retain) UIAlertView *alert;
@property (nonatomic, retain) UIAlertView *alert1;

@end

@implementation LibraryViewController
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"myDownLoad" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"denglu" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Rinse" object:nil];
    [_nameLabel release];
    [_imageV release];
    [_tableArray release];
    [_tempArray release];
    [_dateLabel release];
    [_buttonArray release];
    [_tableV release];
    [_alert release];
    [_alert1 release];
    [_readModel release];
    [_teeeeeeArray release];
    [_tableArrays release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.tempArray = [NSMutableArray array];
        self.buttonArray = [NSMutableArray array];
        self.teeeeeeArray = [NSMutableArray array];
        self.tableArrays = [NSMutableArray array];

        self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 80, self.view.frame.size.width, self.view.frame.size.height - 49) style:UITableViewStyleGrouped];
        [_tableV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"libraryCell"];
        
        _tableV.delegate = self;
        _tableV.dataSource = self;
        [self.view addSubview:_tableV];
        [_tableV release];

    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self readData];

    [self createView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rinse) name:@"Rinse" object:nil];
    self.navigationController.navigationBar.barTintColor = kBlueColor;
    self.navigationController.navigationBar.hidden = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createAlert) name:@"myDownLoad" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(denglu) name:@"denglu" object:nil];
    _SelectDelecttt = 0;//不编辑
    NSLog(@"///////////////");
    [self createDelete];
}
#pragma mark - 
#pragma mark 通知刷新界面

- (void)rinse
{
    [self readData];
    if ([_tableArray count] != 0) {
        if ([[_tableArray objectAtIndex:0] isEqualToString:@""]) {
            [_tableArray removeAllObjects];
            [_tableArrays removeAllObjects];
        }
    }
    [_tableV reloadData];
}
- (void)Action:(id)sender
{
     NSLog(@"aaaaaaaaaaaaaaa");
    [self readData];
    [_tableV reloadData];
}
#pragma mark -
#pragma mark 读取数据库
- (void)readData
{
    [_tableArray removeAllObjects];
    [_tableArrays removeAllObjects];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSInteger nid = [[user objectForKey:@"nid"] integerValue];
    DetailModel *model = [[DetailBace searchDetail:nid] firstObject];
    [self.tableArray addObjectsFromArray: [model.detail_tit componentsSeparatedByString:@"$$"]];
    [self.tableArrays addObjectsFromArray:[model.detail_http componentsSeparatedByString:@"$$"]];
    if ([_tableArray count] != 0) {
        if ([[_tableArray objectAtIndex:0] isEqualToString:@""]) {
            [_tableArray removeAllObjects];
            [_tableArrays removeAllObjects];
        }
    }
#warning 修改
    for (int i = 0 ; i < [_tableArray count]; i++) {
        [self.teeeeeeArray addObject:@"0"];
    }

    NSLog(@"!!!!!!!!!%@", _tableArray);
    _numChapter = [_tableArray count];
}

#pragma mark -
#pragma mark 我的下载alert
- (void)createAlert
{
    self.alert = [[UIAlertView alloc] initWithTitle:nil message:@"收藏文章后,才能下载文章" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    _alert.tintColor = [UIColor yellowColor];
    [_alert show];
    
    //两秒后alert消失
    [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(perform) userInfo:nil repeats:NO];
    [_alert release];
}
- (void)perform
{
    [_alert dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)createView1
{
    if ([_tableArray count] == 0) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(_tableV.frame.size.width / 2, _tableV.frame.size.height / 2, 300, 60);
        [button setCenter:CGPointMake(150, 30)];
        [self.view addSubview:button];
        [button release];
    }
}

#pragma mark -
#pragma mark 个人列表
- (void)createView
{
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80)] autorelease];
    view.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:view];
    [view release];
    self.imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"]];
    [_imageV setCenter:CGPointMake(40.0f, 40.0f)];
    _imageV.layer.cornerRadius = 30;
    _imageV.layer.masksToBounds = YES;
    [view addSubview:_imageV];
    [_imageV release];
    NSString *http = @"";
    NSString *tit = @"";
    for (int i = 0; i < [_tableArray count]; i++) {
        if (http.length == 0) {
            http = [NSString stringWithFormat:@"%@%@",http,[_tableArrays objectAtIndex:i]];
            tit = [NSString stringWithFormat:@"%@%@",tit,[_tableArray objectAtIndex:i]];
            
        }else{
            http = [NSString stringWithFormat:@"%@$$%@",http,[_tableArrays objectAtIndex:i]];
            tit = [NSString stringWithFormat:@"%@$$%@",tit,[_tableArray objectAtIndex:i]];
        }
    }
    //馆主名
    float num = (100 / 375.0f) * self.view.frame.size.width;
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(num, 20, 200, 20)];
    _nameLabel.text = @"用户名";
    _nameLabel.textColor = [UIColor purpleColor];
    _nameLabel.textAlignment = NSTextAlignmentLeft;
    [view addSubview:_nameLabel];
    [_nameLabel release];

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *judge = [user objectForKey:@"login"];
    if ([judge isEqualToString:@"yes"]) {
        NSString *name = [user objectForKey:@"name"];
        if (name != nil) {
            NSString *path = [user objectForKey:@"image"];
            NSURL *url = [NSURL URLWithString:path];
            NSData * data = [NSData dataWithContentsOfURL:url];
            UIImage *iam = [UIImage imageWithData:data];
            _imageV.image = iam;
            _nameLabel.text = name;
        }
    }
    
    //收藏数目及申请时间
    self.dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(num, 50, 200, 15)];
    _dateLabel.text = [NSString stringWithFormat:@"%ld篇收藏", _numChapter];
    _dateLabel.tag = 333;
    [_dateLabel setFont:[UIFont systemFontOfSize:13]];
    _dateLabel.textAlignment = NSTextAlignmentLeft;
    [view addSubview:_dateLabel];
    [_dateLabel release];
    [_tableV.tableHeaderView addSubview: view];
    [_tableV reloadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Action:) name:@"reloadData" object:nil];
}

- (void)denglu
{
    [_tableArray removeAllObjects];
    [_tableArrays removeAllObjects];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *judge = [user objectForKey:@"login"];
    NSInteger nid = [[user objectForKey:@"nid"] integerValue];
    DetailModel *model = [[DetailBace searchDetail:nid] firstObject];
    [self.tableArray addObjectsFromArray: [model.detail_tit componentsSeparatedByString:@"$$"]];
    [self.tableArrays addObjectsFromArray:[model.detail_http componentsSeparatedByString:@"$$"]];
    if ([judge isEqualToString:@"yes"]) {
        NSString *name = [user objectForKey:@"name"];
        if (name != nil) {
            NSString *path = [user objectForKey:@"image"];
            NSURL *url = [NSURL URLWithString:path];
            NSData * data = [NSData dataWithContentsOfURL:url];
            UIImage *iam = [UIImage imageWithData:data];
            _imageV.image = iam;
            _nameLabel.text = name;
            
        }
    }
    if ([judge isEqualToString:@"no"]) {
        _imageV.image = [UIImage imageNamed:@"1.png"];
        _nameLabel.text = @"好哈腰";
    }
    [_tableV reloadData];
}
#pragma mark -
#pragma mark 编辑收藏文章

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    _dateLabel.text = [NSString stringWithFormat:@"%ld篇收藏", [_tableArray count]];

    if (!_logined) {

    }
    return [_tableArray count] ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


    static NSString *cellI = @"libraryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellI];
    if (!cell) {
        cell = [[[LibraryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellI] autorelease];
    }

    NSString *tabelText = [[_tableArray objectAtIndex:indexPath.row] stringByReplacingOccurrencesOfString:@"**" withString:@""];
    cell.textLabel.text = tabelText;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReadingRoomModel *readM = [[[ReadingRoomModel alloc] init] autorelease];
//    DetailModel *model =[_tableArray objectAtIndex:indexPath.row];
//    NSLog(@"**********%@", model.detail_http);

    NSMutableArray *big = [NSMutableArray array];
    NSString *path = [_tableArrays objectAtIndex:indexPath.row];
    NSRange range = [path rangeOfString:@"**"];
    if (range.length == 0) {
    NSArray * array = [path componentsSeparatedByString:@"?"];
    NSString *last = [array lastObject];
    NSArray *arr = [last componentsSeparatedByString:@"&"];
    for (NSString *str in arr) {
        NSArray *s = [str componentsSeparatedByString:@"="];
        [big addObject:[s lastObject]];
    }
    NSLog(@"%@",big);
    readM.os = [big objectAtIndex:0];
    readM.ver = [big objectAtIndex:1];
    readM.op = [big objectAtIndex:2];
    readM.cid = [big objectAtIndex:3];
    readM.aid = [big objectAtIndex:4];
    readM.p = [big objectAtIndex:5];
    readM.w = [big objectAtIndex:6];
    readM.cFrom = [big objectAtIndex:7];
    DetailsViewController *det = [[DetailsViewController alloc] init];
    det.parameter = readM;
#warning 修改
    if (_SelectDelecttt == 0) {
        [self presentViewController:det animated:YES completion:nil];
    }else{
        if ([[_teeeeeeArray objectAtIndex:indexPath.row]  isEqualToString:@"0"]) {
            [_teeeeeeArray replaceObjectAtIndex:indexPath.row withObject:@"1"];
        }else if ([[_teeeeeeArray objectAtIndex:indexPath.row] isEqualToString:@"1"]) {
            [_teeeeeeArray replaceObjectAtIndex:indexPath.row withObject:@"0"];
        }
    }

    [det release];
    }else{
        HomePoltController * polt = [[HomePoltController alloc] init];
        polt.path = [path stringByReplacingOccurrencesOfString:@"**" withString:@""];
        polt.poltTitle = [[_tableArray objectAtIndex:indexPath.row] stringByReplacingOccurrencesOfString:@"**" withString:@""];
        [self presentViewController:polt animated:NO completion:nil];
        [polt release];

    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

#pragma mark -
#pragma mark cell样式编辑(处于编辑状态, 获得编辑样式, 提交样式)
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_SelectDelecttt == 0) {//编辑状态
        return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
    }
    return UITableViewCellEditingStyleDelete;

}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [self.tableArray addObjectsFromArray:[DetailBace searchAllEdit]];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_tableArrays removeObjectAtIndex:indexPath.row];
        [_tableArray removeObjectAtIndex:indexPath.row];
        NSString *http = @"";
        NSString *tit = @"";
        for (int i = 0; i < [_tableArray count]; i++) {
            if (http.length == 0) {
                http = [NSString stringWithFormat:@"%@%@",http,[_tableArrays objectAtIndex:i]];
                tit = [NSString stringWithFormat:@"%@%@",tit,[_tableArray objectAtIndex:i]];
                
            }else{
                http = [NSString stringWithFormat:@"%@$$%@",http,[_tableArrays objectAtIndex:i]];
                tit = [NSString stringWithFormat:@"%@$$%@",tit,[_tableArray objectAtIndex:i]];
            }
        }
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSInteger nid = [[user objectForKey:@"nid"] integerValue];
        [DetailBace updateDetail_tit:tit detail_id:nid detail_http:http];
//        DetailModel *model = [self.tableArray objectAtIndex:indexPath.row];
//        [DetailBace deleteFromDetailWithDetail_id:model.detail_id];
//        [_tableArray removeObject:model];
        _logined = NO;
        [_tableV reloadData];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Action:) name:@"reloadData" object:nil];
    }
}
#pragma mark -
#pragma mark 选择性删除
- (void)createDelete
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectSelect) name:@"DeleteSelect" object:nil];
}
- (void)selectSelect
{
    if (_SelectDelecttt == 0) {
        if ([_tableArray count] == 0) {
            [self readData];
        }else{

        }

        [_tableV setEditing:YES animated:YES];
        _SelectDelecttt = 1;
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"点击选择批量删除" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//        [alert release];

    }else if (_SelectDelecttt == 1){
        [_tableV setEditing:NO animated:NO];
        _SelectDelecttt = 0;
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSInteger nid = [[user objectForKey:@"nid"] integerValue];
        DetailModel *model = [[DetailBace searchDetail:nid] firstObject];
        [_tableArray removeAllObjects];
        [_tableArrays removeAllObjects];
        [self.tableArray addObjectsFromArray: [model.detail_tit componentsSeparatedByString:@"$$"]];
        [self.tableArrays addObjectsFromArray:[model.detail_http componentsSeparatedByString:@"$$"]];
        if ([_tableArray count] != 0) {
            if ([[_tableArray objectAtIndex:0] isEqualToString:@""]) {
                [_tableArray removeAllObjects];
                [_tableArrays removeAllObjects];
            }
        }

//        self.tableArray = [DetailBace searchAllEdit];

        for (int i = 0; i < [_teeeeeeArray count]; i++) {
            if ([[_teeeeeeArray objectAtIndex:i] isEqualToString:@"1"]) {
//                DetailModel *model = [_tableArray objectAtIndex:i];
//                [DetailBace deleteFromDetailWithDetail_id: model.detail_id];
                [_tableArray removeObjectAtIndex:i];
                [_tableArrays removeObjectAtIndex:i];
                NSString *http = @"";
                NSString *tit = @"";
                for (int i = 0; i < [_tableArray count]; i++) {
                    if (http.length == 0) {
                        http = [NSString stringWithFormat:@"%@%@",http,[_tableArrays objectAtIndex:i]];
                        tit = [NSString stringWithFormat:@"%@%@",tit,[_tableArray objectAtIndex:i]];
                        
                    }else{
                        http = [NSString stringWithFormat:@"%@$$%@",http,[_tableArrays objectAtIndex:i]];
                        tit = [NSString stringWithFormat:@"%@$$%@",tit,[_tableArray objectAtIndex:i]];
                    }
                }
                
                [DetailBace updateDetail_tit:tit detail_id:nid detail_http:http];
            }
        }
    }
    [_tableArray removeAllObjects];
    [_tableArrays removeAllObjects];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSInteger nid = [[user objectForKey:@"nid"] integerValue];
    DetailModel *model = [[DetailBace searchDetail:nid] firstObject];
    [self.tableArray addObjectsFromArray: [model.detail_tit componentsSeparatedByString:@"$$"]];
    [self.tableArrays addObjectsFromArray:[model.detail_http componentsSeparatedByString:@"$$"]];
    if ([_tableArray count] != 0) {
        if ([[_tableArray objectAtIndex:0] isEqualToString:@""]) {
            [_tableArray removeAllObjects];
            [_tableArrays removeAllObjects];
        }
    }
    [_tableV reloadData];
}
#pragma mark -
#pragma mark 触发事件,返回图书界面(添加透明button,触发跳转页面事件)
- (void)createLabelCenter
{
    if ([_tableArray count] == 0) {
        _logined = YES;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, self.view.frame.size.height / 2 - 50, self.view.frame.size.width - 60, 60)];
        [_tableV setBackgroundColor:[UIColor clearColor]];
        [label setFont:[UIFont systemFontOfSize:18]];
        label.numberOfLines = 0;
        [label setTextColor:[UIColor blueColor]];
        [self.view addSubview:label];
        [label release];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)buttonCancel:(id)sender
{
    //    [UIView animateWithDuration:0.1f animations:^{
    //        _field.frame = CGRectMake(64, 4, 300, 36);
    //        [UIView animateWithDuration:0 animations:^{
    //            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    //            button.frame = CGRectMake(4, 7, 30, 30);
    //            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    //            [button setImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:UIControlStateNormal];
    //            [_view1 addSubview:button];
    //        }];
    //    }];
    //    [[_view1.subviews objectAtIndex:1] removeFromSuperview];
    //    [_field resignFirstResponder];
}
@end
